package com.example.service;

import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.XmlWebApplicationContext;

import java.util.logging.Logger;

@Service
public class SysBeanServiceImpl implements SysBeanService, ApplicationContextAware, BeanPostProcessor {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(SysBeanServiceImpl.class);

    Logger logger = Logger.getLogger(SysBeanServiceImpl.class.getName());

    private DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        XmlWebApplicationContext xmlWebApplicationContext = (XmlWebApplicationContext) applicationContext;
        this.defaultListableBeanFactory = (DefaultListableBeanFactory) xmlWebApplicationContext.getBeanFactory();
    }

    /****
     * 注册bean
     * @param beanName
     * @param bean
     */
    @Override
    public void registerSingleton(String beanName, Object bean) {
        this.defaultListableBeanFactory.registerSingleton(beanName, bean);
        this.defaultListableBeanFactory.getBean(beanName);
    }

    /***
     * 删除bean
     * @param beanName
     */
    @Override
    public void removeSingleton(String beanName) {
        if (this.defaultListableBeanFactory.containsSingleton(beanName)) {
            this.defaultListableBeanFactory.destroySingleton(beanName);
        }
        if (this.defaultListableBeanFactory.containsBeanDefinition(beanName)) {
            this.defaultListableBeanFactory.removeBeanDefinition(beanName);
        }
    }
}
